package tinybase.exec;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import tinybase.basic.BytePointer;
import tinybase.basic.RC;
import tinybase.pf.PF_BufferMgr;
import tinybase.pf.HashTable;
import tinybase.pf.PF_PageHandle;
import tinybase.pf.PageNum;

public class Main {
	
	public static void main(String[] args)
	{
		String fileName = "test.dat";

		try
		{
			/**
			 * Write two integers to test.dat
			 */
			File myFile = new File(fileName);
			myFile.createNewFile();
			FileOutputStream out = new FileOutputStream(myFile);
			
			ByteBuffer bbuf = ByteBuffer.allocate(8).putInt(1);
			bbuf.putInt(2);
			out.write(bbuf.array());
			out.close();
			
			/**
			 * Read two integers from test.dat
			 */
			FileInputStream in = new FileInputStream(myFile);
			
			byte[] bbuf1 = new byte[8];
			in.read(bbuf1, 0, 8);
			in.close();
			
			PF_PageHandle phd = new PF_PageHandle();
			phd.setData(bbuf1);
			
			/**
			 * Test the way of passing parameter
			 */
			BytePointer ptr = new BytePointer();
			phd.getData(ptr);
			byte[] bbuf2 = ptr.getArray();
			
			/**
			 * Test of result in bbuf2
			 */
			int[] testArr = new int[2];
			testArr[0] = 0;
			testArr[0] += (bbuf2[4] & 0xFF) << 24;
			testArr[0] += (bbuf2[5] & 0xFF) << 16;
			testArr[0] += (bbuf2[6] & 0xFF) << 8;
			testArr[0] += (bbuf2[7] & 0xFF);
			testArr[1] = 0;
			testArr[1] += (bbuf2[0] & 0xFF) << 24;
			testArr[1] += (bbuf2[1] & 0xFF) << 16;
			testArr[1] += (bbuf2[2] & 0xFF) << 8;
			testArr[1] += (bbuf2[3] & 0xFF);
			
			System.out.println(testArr[0]);
			System.out.println(testArr[1]);
		}
		catch (IOException err) {
			System.out.println(err.toString());
		}
		
		/*
		 * test BufferMgr
		 */
		
		
		PF_BufferMgr bm= new PF_BufferMgr(4076);
		PageNum pageNum= new PageNum(5);
		bm.setHashTable(new HashTable(5));
		
		FileDescriptor fd= new FileDescriptor();
		BytePointer ppBuffer= new BytePointer();
		boolean bMultiplePins= true;
		try {
			FileInputStream fis= new FileInputStream(new File("files/text"));
			fd= fis.getFD();
			RC rc= bm.getPage(fd, pageNum, ppBuffer, bMultiplePins);
			assertEquals(RC.PF_SUCCESS, rc);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

